package com.totcy.baselibrary.base.mvpbase;

import android.content.Context;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

/**
 * @version V1.0
 * @ClassName: BasePresenter
 * @Description: :<B>基础Presenter层实现类，对View层和Presenter做了实例性的处理</B><br>
 * @author by: tu
 * @date 2016/08/17 22:21
 */

public abstract class BasePresenterImpl<V extends BaseView, M extends BaseModel> implements BasePresenter {
    private Reference<V> reference;
    protected Context mContext;
    private M mBaseModelImpl;

    public BasePresenterImpl(Context context) {
        this.mContext = context;
        //绑定model层
        this.mBaseModelImpl = attachModel();
    }

    public abstract M attachModel();

    public M getModel() {
        return mBaseModelImpl;
    }

    public void attachView(V view) {
        reference = new WeakReference<>(view);
    }

    @Override
    public void detachView() {
        if (reference != null) {
            reference.clear();
            reference = null;
        }
    }

    //解除model层的绑定
    @Override
    public void detachModel() {
        if (mBaseModelImpl != null) {
            //解绑 取消请求
            mBaseModelImpl.canCelRequest();
            mBaseModelImpl = null;
        }
    }

    public V getView() {
        return reference.get();
    }

    @Override
    public boolean isViewAttached() {
        return reference != null && reference.get() != null;
    }

    @Override
    public boolean isModelAttached() {
        return mBaseModelImpl != null ;
    }
}
